﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.Data;

namespace DevExpressDemos.Controls.GridControl
{
    public partial class 显示汇总 : 显示行号
    {
        public 显示汇总()
        {
            InitializeComponent();
            gridView1.OptionsView.ShowFooter = true;        //显示汇总栏
            SetSumCol(gridView1.Columns["filedname3"]);
            SetSumCol(gridView1.Columns["filedname5"]);
            gridView1.Columns["filedname2"].SummaryItem.SummaryType = SummaryItemType.Custom;//设置自定义汇总
            gridView1.Columns["filedname2"].SummaryItem.DisplayFormat = "CUSTOM={0:0.##}";
            gridView1.CustomSummaryCalculate += View_CustomSummaryCalculate;//绑定自定义汇总事件
        }
        private void SetSumCol(GridColumn gridColumn)
        {
            gridColumn.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
            gridColumn.SummaryItem.DisplayFormat = "SUM={0:0.##}";
        }

        /// <summary>
        /// 临时变量(存放自定义汇总的结果)
        /// </summary>
        private decimal sumAmt = 0;
        /// <summary>
        /// 自定义汇总
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void View_CustomSummaryCalculate(object sender, DevExpress.Data.CustomSummaryEventArgs e)
        {
            if (((DevExpress.XtraGrid.GridSummaryItem)e.Item).FieldName != "filedname2")
                return;
            switch (e.SummaryProcess)
            {
                case CustomSummaryProcess.Start:
                    sumAmt = 0;
                    break;
                case CustomSummaryProcess.Calculate:
                    sumAmt += Convert.ToDecimal(IsNull(e.FieldValue, 0)) * Convert.ToDecimal(IsNull(gridView1.GetRowCellValue(e.RowHandle, "filedname1"), 0));
                    break;
                case CustomSummaryProcess.Finalize:
                    e.TotalValue = Math.Round(sumAmt, 4);
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 判断是否为Null/DBNull,是则返回newobject
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="newobj"></param>
        /// <returns></returns>
        private object IsNull(object obj, object newobj)
        {
            return (obj == null || obj == DBNull.Value) ? newobj : obj;
        }
    }
}